﻿<%@ WebHandler Language="C#" Class="keyAddHandler" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using Chenxin.Lib.Utility;

public class keyAddHandler : AjaxHandlerBase
{

        
    //构造函数
    public keyAddHandler()
    {
        //钥匙添加
        htTypePermit.Add("add", Constants.Permit_KeyAdd);
        //钥匙修改
        htTypePermit.Add("edit", Constants.Permit_KeyEdit);
        //钥匙使用
        htTypePermit.Add("addkeyuse", Constants.Permit_KeyUse);
        //钥匙使用修改
        htTypePermit.Add("editkeyuse", Constants.Permit_KeyUse);
    }
    
    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            case "validate":
                strResponse = validate(context);
                break;
            case "add":
                strResponse = insert(context);
                break;
            case "addkeyuse":
                strResponse = insertKeyUse(context);
                break;
           case "validatecode":
                strResponse = validateCode(context);
                break;    
           case "getlist":
                strResponse = getKeyList(context);
                break;
            case "getkeyuselist":
                strResponse = getKeyUseInfoList(context);
                break;
            case "getkeyuseinfo":
                strResponse = getKeyUseInfo(context);
                break;
            case "getkeylist":
                strResponse = getHouseKeyList(context);
                break;
            case "getmodel":
                strResponse = GetModel(context);
                break;
            case "editkeyuse":
                strResponse = EditUseInfo(context);
                break;
            case "edit":
                strResponse = EditKeyReceiption(context);
                break;
            case "del":
                strResponse = delKeyUseInfo(context);
                break;
            case "getkeyreceiptionmodel":
                strResponse = getKeyModel(context);
                break;
            case "editkeyreceiption":
                strResponse = EditKeyReceiption(context);
            break;
                case "delkeyreceiption":
                strResponse = delKeyReceiption(context);
            break;   
                
            default:
                break;
        }
        context.Response.Write(strResponse);
     }
    
    //*******************************************
    //功能概要       ：添加钥匙
    //参数説明       ：
    //返回值説明     ：
    //功能詳細       ：添加钥匙
    //作成者         ：chen.yugong
    //作成日         ：2010-03-04
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string insert(HttpContext context)
    {
        try
        {
            //转换成实体
            Chenxin.Lib.House.Entity.House_KeyReceiptionInfo model = (Chenxin.Lib.House.Entity.House_KeyReceiptionInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_KeyReceiptionInfo));
            if (model.ReceiptionId == null)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "钥匙标识丢失，请联系管理员！");
            if (model.HouseId == null)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "房源标识丢失，请联系管理员！");
            Chenxin.Lib.House.Entity.House_BaseInfo house_BaseInfo = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(model.HouseId);
            house_BaseInfo.IsHavekey = true;
            Chenxin.Lib.House.DAL.House_BaseInfo.Update(house_BaseInfo);

            //清除缓存
            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, house_BaseInfo.HouseId);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            cs.Delete(strCachKey);
            
            model.ReceiptionId = Guid.NewGuid();
            model.Status = 0;
            model.AddTime = DateTime.Now;
            model.CityId = CurrentUserInfo.CityId;
            model.CityName = CurrentUserInfo.CityName;
            model.CompanyId = CurrentUserInfo.CompanyId;
            model.CompanyName = CurrentUserInfo.CompanyName;
            model.DepartId = CurrentUserInfo.DepartId;
            model.Depart = CurrentUserInfo.DepartName; 
            model.AddPerson = CurrentUserInfo.UserName;
            model.AddPersonId = CurrentUserInfo.UserId;
            Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.Add(model);

            //添加用户操作日志 2010-5-11 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "添加了一个钥匙:" + model.ReceiptionCode + "",
                    OperationType.OperationTypeComboList()["OprType_KeyAdd"].ToString());
            
            return string.Format("{{success:'1',msg:'{0}',data:''}}", "钥匙添加成功！");
        }
         catch (Exception ex)
         {
             return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
         }
     }
    
    //*******************************************
    //功能概要       ：添加钥匙使用记录
    //参数説明       ：
    //返回值説明     ：
    //功能詳細       ：添加钥匙使用记录
    //作成者         ：chen.yugong
    //作成日         ：2010-03-04
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string insertKeyUse(HttpContext context)
    {
        try
        {
            //转换成实体
            Chenxin.Lib.House.Entity.House_KeyUsedInfo model = (Chenxin.Lib.House.Entity.House_KeyUsedInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_KeyUsedInfo));
            if (model.KeyReceiptionId == null)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "钥匙标识丢失，请联系管理员！");

            string keyUserCode = context.Request["keyUserCode"];
            Chenxin.Lib.Passport.Entity.Hr_UserInfo userInfo = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityByCode(keyUserCode);
            if (userInfo != null)
            {
                model.KeyId=Guid.NewGuid();
                model.keyUserId = userInfo.UserId;
                model.keyUserName = userInfo.UserName;
                model.AddPersonId= CurrentUserInfo.UserId;
                model.AddTime = DateTime.Now;
             }
            else
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "用户不存在！");
            }
            if (20==model.InOrOut)
            {
                
            Chenxin.Lib.House.Entity.House_KeyReceiptionInfo house_KeyReceiptionInfo =  Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetModel(model.KeyReceiptionId);
            if (house_KeyReceiptionInfo == null)
                return string.Format("{{success:'0',msg:'{0}：{0}',data:''}}", "钥匙标识丢失，请联系管理员！");
            if (house_KeyReceiptionInfo.HouseId == null)
                return string.Format("{{success:'0',msg:'{0}：{0}',data:''}}", "房源标识丢失，请联系管理员！");
            Chenxin.Lib.House.Entity.House_BaseInfo house_BaseInfo = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(house_KeyReceiptionInfo.HouseId);
            if (house_BaseInfo==null)
                return string.Format("{{success:'0',msg:'{0}：{0}',data:''}}", "房源信息丢失，请联系管理员！");
            house_BaseInfo.IsHavekey=false;
            Chenxin.Lib.House.DAL.House_BaseInfo.Update(house_BaseInfo);
            }
            Chenxin.Lib.House.DAL.House_KeyUsedInfo.Add(model);
            
            //添加用户操作日志 2010-5-11 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "添加了一个钥匙记录:" + model.keyUserName + "",
                    OperationType.OperationTypeComboList()["OprType_UseKeyAdd"].ToString());
            
            return string.Format("{{success:'1',msg:'{0}',data:''}}", "钥匙记录添加成功！");
        }
         catch (Exception ex)
         {
             return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
         }
     }
    
    //*******************************************
    //功能概要       ：编号验证
    //参数説明       ：
    //返回值説明     ：
    //功能詳細       ：编号验证
    //作成者         ：chen.yugong
    //作成日         ：2010-03-04
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string validate(HttpContext context)
    {
        try
        {
            string keyCode = context.Request["keyAddCode"];
            Chenxin.Lib.House.Entity.House_KeyReceiptionInfo house_KeyReceiptionInfo = new Chenxin.Lib.House.Entity.House_KeyReceiptionInfo();
            string strWhere = string.Format("ReceiptionCode = '{0}'", keyCode);
            System.Collections.Generic.List<Chenxin.Lib.House.Entity.House_KeyReceiptionInfo> list = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetListArray(strWhere);
            if (list.Count > 0)
            {
                return "0";
            }
            else
            {
                return "1";
            }
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
     }

    //*******************************************
    //功能概要       ：验证工号
    //参数説明       ：personId 工号
    //返回值説明     ：void
    //功能詳細       ：验证工号
    //作成者         ：chen.yugong 
    //作成日         ：2010-03-02
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string validateCode(HttpContext context)
    {
        try
        {
            string personId = context.Request["keyUserCode"];
            Chenxin.Lib.Passport.Entity.Hr_UserInfo userInfo = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityByCode(personId);
            if (userInfo != null)
            {
                return string.Format("{{success:'1',msg:'成功',data:{{model:{0}}}}}", Chenxin.Lib.Utility.JsonHelp.Convert2Json(userInfo));
            }
            else
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "用户不存在！");
            }
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }
    
    //*******************************************
    //功能概要       ：获得钥匙使用详细信息
    //参数説明       ：
    //返回值説明     ：
    //功能詳細       ：获得钥匙使用详细信息
    //作成者         ：chen.yugong
    //作成日         ：2010-03-04
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string getKeyUseInfo(HttpContext context)
    {

        try
        {
            string keyuseid = context.Request["keyuseid"];
            if (string.IsNullOrEmpty(keyuseid))
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "钥匙标识丢失，请联系管理员！");
            Chenxin.Lib.House.Entity.House_KeyReceiptionInfo house_KeyReceiptionInfo = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetModel(new Guid(keyuseid));
            if (house_KeyReceiptionInfo == null) {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "钥匙使用信息丢失，请联系管理员！");
            }
            if (house_KeyReceiptionInfo.HouseId==Guid.Empty)
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，房源标识丢失");
            }
            Chenxin.Lib.House.Entity.House_BaseInfo item = null;
            //从缓存服务器读取房源信息
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            //string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, house_KeyReceiptionInfo.HouseId);
            //item = cs.GetObject(strCachKey) as Chenxin.Lib.House.Entity.House_BaseInfo;
            //if (!cs.Hit)//若未命中
            //{
                item = Chenxin.Lib.House.BLL.House_BaseInfo.GetHouseInfoEntity(house_KeyReceiptionInfo.HouseId.ToString());
            //    cs.Set(strCachKey, item, DateTime.Now.AddHours(1));
            //}
            
            if (item == null)
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，找不到对应的房源");
            }

            return string.Format("{{success:'1',msg:'成功',data:{{houseinfo:{0}}}}}",Chenxin.Lib.Utility.JsonHelp.Convert2Json(item));
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }
    
    //*******************************************
    //功能概要       ：获得钥匙使用信息
    //参数説明       ：
    //返回值説明     ：
    //功能詳細       ：获得钥匙使用信息
    //作成者         ：chen.yugong
    //作成日         ：2010-03-04
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string getKeyList(HttpContext context)
    {

        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数

            string fieldlist = "ReceiptionId,ReceiptionCode,HouseAddress,KeyCount,Status,GetKeyDay,AddPerson,AddTime";
            string fieldtablelist = "ReceiptionId,ReceiptionCode,HouseAddress,KeyCount,CASE Status when '0'  then '正常' when '10' then '借出' end as Status ,GetKeyDay,AddPerson,AddTime";
            string orderfield = "House_KeyReceiptionInfo.GetKeyDay desc";

            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid employee = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);
            
            //判断权限范围/////////////////////////////////////////////
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (employee != Guid.Empty)
                sb.AppendFormat(" AND (AddPersonId = '{0}') ", employee);
            else if (departs != Guid.Empty)
                sb.AppendFormat(" AND (DepartId = '{0}')", departs);
            else if (businessdistrict != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");

                sb.AppendFormat(" AND (DepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (company != Guid.Empty)
                sb.AppendFormat(" AND (DepartId in (Select DepartId from v_Hr_DepartmentInfo where CompanyId = '{0}'))", company);
            else if (city != Guid.Empty)
                sb.AppendFormat(" AND (DepartId in (Select DepartId from v_Hr_DepartmentInfo where CityId = '{0}'))", city);
            else
                sb.AppendFormat(" AND (DepartId in (Select DepartId from v_Hr_DepartmentInfo where CompanyId = '{0}'))", CurrentUserInfo.CompanyId);
                
            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            //查看所有钥匙权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllKey))
            {
                sb1.Append(" (1=1) ");
            }
            //查看城市钥匙权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityKey))
            {
                sb1.Append("EXISTS(");
                sb1.Append("Select 1 from v_Hr_User_BaseInfo M ");
                sb1.AppendFormat("WHERE House_KeyReceiptionInfo.AddPersonId = M.Userid AND  M.CityId= '{0}' ", CurrentUserInfo.CityId);
                sb1.Append(")");
            }
            //查看公司钥匙权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyKey))
            {
                sb1.Append("EXISTS(");
                sb1.Append("Select 1 from v_Hr_User_BaseInfo M ");
                sb1.AppendFormat("WHERE House_KeyReceiptionInfo.AddPersonId = M.Userid AND  M.CompanyId= '{0}' ", CurrentUserInfo.CompanyId);
                sb1.Append(")");
            }
            //查看部门钥匙权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewDepartKey))
            {
                sb1.Append("EXISTS(");
                sb1.Append("Select 1 from v_Struct_UserDepartRelation M ");
                sb1.AppendFormat("WHERE (House_KeyReceiptionInfo.DepartId = M.Departid AND  M.Userid= '{0}') ", CurrentUserInfo.UserId);
                sb1.Append(")");
            }
            else
            {
                sb1.AppendFormat(" AddPersonId = '{0}'", CurrentUserInfo.UserId);
            }

            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());

            string stime = context.Request.QueryString["stime"];
            string etime = context.Request.QueryString["etime"];
            string strquery = context.Request.QueryString["strquery"];
            string keystatus = context.Request.QueryString["keystatus"];
            if (!String.IsNullOrEmpty(stime))
            {
                sb1.Append(string.Format(" AND convert(varchar(10),(convert(datetime,GetKeyDay,120)),120)  >= '{0}'", (stime)));
            }
            if (!String.IsNullOrEmpty(etime))
            {
                sb1.Append(string.Format(" AND convert(varchar(10),(convert(datetime,GetKeyDay,120)),120)  <= '{0}'", (etime)));
            }
            if (!String.IsNullOrEmpty(strquery))
            {
                sb1.Append("AND (ReceiptionCode Like  '%" + strquery + "%' OR HouseAddress LIKE '%" + strquery + "%' OR HouseCode LIKE '%" + strquery + "%')");
            }
            if (!String.IsNullOrEmpty(keystatus))
            {
                sb1.Append(string.Format(" and Status= '{0}'", keystatus));
            }
            //判断权限范围结束////////////////////////////////////////////


            System.Data.DataSet dskeylist = null;
            dskeylist = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetList(
                iPageIndex, iPageSize, orderfield, "House_KeyReceiptionInfo", sb1.ToString(), fieldlist, fieldtablelist, true);
            int count = (int)dskeylist.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetKeyListHtml(dskeylist, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml);
            }
            dskeylist.Dispose();
            dskeylist = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }

    /// <summary>
    /// 返回列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private bool GetKeyListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        try
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
            sb.Append("<thead><tr>");
            //sb.Append("<th width=\"12%\">操作</th>");
            sb.Append("<th width=\"12%\">钥匙编号</th>");
            sb.Append("<th width=\"10%\">钥匙数量</th>");
            sb.Append("<th width=\"10%\">状态</th>");
            sb.Append("<th width=\"10%\">添加人</th>");
            sb.Append("<th width=\"15%\">收取日期</th>");
            sb.Append("<th >地址</th>");
            sb.Append("<th width=\"15%\">建档日期</th>");
            sb.Append("</tr></thead><tbody>");
            int i = 0;
            foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
            {
                if (i % 2 == 0)
                    sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", row["ReceiptionId"].ToString());
                else
                    sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist bluebgcolor\">", row["ReceiptionId"].ToString());

              /*  sb.AppendFormat("<td>{0} {1} {2} </td>",
                string.Format("<a name=\"{0}\" class=\"a_key_view\" href=\"#\">查看</a>", row["ReceiptionId"].ToString()),
                string.Format("<a name=\"{0}\" class=\"a_key_edit\" href=\"#\">修改</a>", row["ReceiptionId"].ToString()),
                string.Format("<a name=\"{0}\" class=\"a_key_del\" href=\"#\">删除</a>", row["ReceiptionId"].ToString()));
               */
                //钥匙编号
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ReceiptionCode", ""));
                //状态
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "KeyCount", ""));
                //状态
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Status", ""));
                //添加人
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "AddPerson", ""));
                //取得时间
                sb.AppendFormat("<td>{0:yyyy-MM-dd}</td>", Convert.ToDateTime(Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "GetKeyDay", "")));
                //地址
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseAddress", ""));
                sb.AppendFormat("<td>{0:yyyy-MM-dd}</td>", Convert.ToDateTime(Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "AddTime", "")));
                sb.Append("</tr>");
                i++;
            }

            sb.Append("</tbody></table>");
            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }

    /// <summary>
    /// 根据参数中的房源ID查询房源跟单数据;
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private string getKeyUseInfoList(HttpContext context)
    {
        try
        {
            Guid keyid = (string.IsNullOrEmpty(context.Request["keyid"])) ? Guid.Empty : new Guid(context.Request["keyid"]);
            if (keyid == Guid.Empty)
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，钥匙标识丢失");
            }

            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 3 : int.Parse(context.Request["pagesize"]);//页记录数
            string fieldlist = "InOrOut,ActionDay,keyUserName,KeyId";
            string fieldtablelist = "case House_KeyUsedInfo.InOrOut when '0' then '归还' when '10' then '借出' when '20' then '收回' end as InOrOut,ActionDay,keyUserName,KeyId";
            string orderfield = "House_KeyUsedInfo.AddTime desc";
            string strwhere = string.Format("(KeyReceiptionId='{0}')", keyid);

            System.Data.DataSet ds = null;
            ds = Chenxin.Lib.House.DAL.House_KeyUsedInfo.GetList(iPageIndex, iPageSize, orderfield, "House_KeyUsedInfo", strwhere, fieldlist, fieldtablelist, true);
            int count = (int)ds.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetListHtml(ds, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
            }
            ds.Dispose();
            ds = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }

    /// <summary>
    /// 生成列表
    /// </summary>
    /// <param name="dslist"></param>
    /// <param name="strHtml"></param>
    /// <returns></returns>
    private bool GetListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
        {
            sb.AppendFormat("<div class=\"infos\" title=\"{0}\"><span class=\"rbpsn\"><a href=\"#\" name=\"{3}\" class=\"tr_searchKeyInfo\">查看</a>&nbsp;<a href=\"#\" name=\"{3}\" class=\"tr_editKeyInfo\">编辑</a> </span><span class=\"rbpsn\">{0}</span><span class=\"rbpsn\">{1}</span><span class=\"rbtim\">{2:yyyy-MM-dd HH:mm}</span> </div>",
            //sb.AppendFormat("<div class=\"infos\" title=\"{0}\"><span class=\"rbpsn\"><a href=\"#\" name=\"{3}\" class=\"tr_searchKeyInfo\">查看</a>&nbsp;<a href=\"#\" name=\"{3}\" class=\"tr_editKeyInfo\">编辑</a>&nbsp;<a href=\"#\" name=\"{3}\" class=\"tr_delKeyInfo\">删除</a></span> <span class=\"rbpsn\">{0}</span><span class=\"rbpsn\">{1}</span><span class=\"rbtim\">{2:yyyy-MM-dd HH:mm}</span> </div>",
            Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "InOrOut", ""),
            Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "keyUserName", ""),
            Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ActionDay", ""),
            Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "KeyId", ""));
        }
        strHtml = sb.ToString();
        return true;
    }

    //*******************************************
    //返回值説明     ：响应字符串
    //功能詳細       ：某一房屋对应跟单信息
    //作成者         ：hejifeng
    //作成日         ：2010-04-27
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string getHouseKeyList(HttpContext context)
    {
        string strRet;
        try
        {
            string houseid = context.Request.Params["houseid"];
            int PageIndex = 1;
            int PageSize = 10;

            //页码        
            if (!string.IsNullOrEmpty(context.Request.Params["pageindex"]))
            {
                PageIndex = int.Parse(context.Request.Params["pageindex"]) + 1;
            }
            //页显示行数
            if (!string.IsNullOrEmpty(context.Request.Params["pagesize"]))
            {
                PageSize = int.Parse(context.Request.Params["pagesize"]);
            }

            string OrderField = "AddTime desc";
            string StrWhere = "HouseId='" + houseid + "'";
            string FieldList = "ReceiptionCode,HouseAddress,KeyCount,Status,GetKeyDay,AddPerson,AddTime";
            string TableFieldList = "ReceiptionCode,HouseAddress,KeyCount,CASE Status when '0'  then '正常' when '10' then '借出' end as Status ,convert(nvarchar(10),GetKeyDay,120),AddPerson,convert(nvarchar(10),AddTime,120)";
            string TableName = "House_KeyReceiptionInfo";

            //根据sql执行查询
            DataSet ds = null;
            if (PageIndex == 1)
            {
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
                string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_INFO_KEY, houseid);
                ds = cs.GetDataSet(strCachKey);

                if (!cs.Hit)
                {
                    ds = Chenxin.Lib.House.DAL.House_KeyUsedInfo.GetList(PageIndex, PageSize, OrderField, TableName, StrWhere, FieldList, TableFieldList, true);
                    if (ds != null)
                        cs.Set(strCachKey, ds, DateTime.Now.AddMinutes(5));
                }
            }
            else
            {

                ds = Chenxin.Lib.House.DAL.House_KeyUsedInfo.GetList(PageIndex, PageSize, OrderField, TableName, StrWhere, FieldList, TableFieldList, true);
            }
       
            strRet = retExecResult(Constants.ExecResult.Succ, "", retPagination(ds));
            return strRet;
        }
        catch (Exception ex)
        {
            strRet = retExecResult(Constants.ExecResult.Error, ex.Message, "");
            return strRet;
        }
    }

    //生成html
    private Constants.Pagination retPagination(DataSet ds)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        sb.Append("<table id=\"showYaoShi\" width=\"100%\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\"><thead>");
        sb.Append("<tr class=\"tab_line4\"><td width=\"90px\"><b>编号</b></td><td><b>房源地址</b></td><td width=\"70px\"><b>钥匙数量</b></td><td width=\"80px\"><b>状态</b></td><td width=\"80px\"><b>获取时间</b></td><td width=\"100px\"><b>添加人</b></td><td width=\"80px\"><b>添加时间</b></td></tr>");
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            sb.AppendFormat("<tr class=\"tab_line5\"><td title=\"{0}\">{0}</td><td  title=\"{1}\">{1}</td><td title=\"{2}\">{2}</td><td title=\"{3}\">{3}</td><td title=\"{4}\">{4}</td><td title=\"{5}\">{5}</td><td title=\"{6}\">{6}</td></tr>", dr[0], dr[1], dr[2], dr[3], dr[4], dr[5], dr[6]);
        }
        sb.Append("</thead></table>");

        Constants.Pagination stuPag = new Constants.Pagination();
        stuPag.count = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
        stuPag.data = sb.ToString();

        return stuPag;
    }

    /// <summary>
    /// 获取Model
    /// </summary>
    /// <param name="context"></param>
    private string GetModel(HttpContext context)
    {
        try
        {
            //转换成实体
            string modelid = context.Request["modelid"];
            if (String.IsNullOrEmpty(modelid))
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "记录标识丢失！");

            //向申请变更表中添加记录
            Chenxin.Lib.House.Entity.House_KeyUsedInfo house_KeyUsedInfo = Chenxin.Lib.House.DAL.House_KeyUsedInfo.GetModel(new Guid(modelid));
            return string.Format("{{success:'1',msg:'成功',data:{{model:{0}}}}}", Chenxin.Lib.Utility.JsonHelp.Convert2Json(house_KeyUsedInfo));
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }

    private string getKeyModel(HttpContext context)
    {
        try
        {
            //转换成实体
            string modelid = context.Request["modelid"];
            if (String.IsNullOrEmpty(modelid))
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "记录标识丢失！");

            //向申请变更表中添加记录
            Chenxin.Lib.House.Entity.House_KeyReceiptionInfo house_KeyUsedInfo = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetModel(new Guid(modelid));
            return string.Format("{{success:'1',msg:'成功',data:{{model:{0}}}}}", Chenxin.Lib.Utility.JsonHelp.Convert2Json(house_KeyUsedInfo));
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }

    /// <summary>
    /// 修改使用钥匙信息
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string EditUseInfo(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.House_KeyUsedInfo model = (Chenxin.Lib.House.Entity.House_KeyUsedInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_KeyUsedInfo));
            if (model.KeyId == null)
                return retExecResult(Constants.ExecResult.Error, "标识丢失，请联系管理员！", "");
            Chenxin.Lib.House.Entity.House_KeyUsedInfo dbModel = Chenxin.Lib.House.DAL.House_KeyUsedInfo.GetModel(model.KeyId);
            
            if(!dbModel.keyUserCode.Equals(model.keyUserCode)) {
                Chenxin.Lib.Passport.Entity.Hr_UserInfo userInfo = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityByCode(model.keyUserCode);
                if (userInfo != null)
                {
                    model.keyUserId = userInfo.UserId;
                    model.keyUserName = userInfo.UserName;
                    model.AddPersonId= CurrentUserInfo.UserId;
                }
                else
                {
                    return string.Format("{{success:'0',msg:'{0}',data:''}}", "用户不存在！");
                }
            }
            
            dbModel.ActionDay=model.ActionDay;
            dbModel.Remarks=model.Remarks;
            dbModel.InOrOut=model.InOrOut;
            Chenxin.Lib.House.DAL.House_KeyUsedInfo.Update(dbModel);
            
            return retExecResult(Constants.ExecResult.Succ, "更新成功", "");
        }
        catch (Exception ex)
        {
            return retExecResult(Constants.ExecResult.Error, "意外错误：" + ex.Message, "");
        }
    }
    
    
        
            /// <summary>
    /// 修改使用钥匙信息
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string EditKeyReceiption(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.House_KeyReceiptionInfo model = (Chenxin.Lib.House.Entity.House_KeyReceiptionInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_KeyReceiptionInfo));
            if (model.ReceiptionId == null)
                return retExecResult(Constants.ExecResult.Error, "标识丢失，请联系管理员！", "");
            Chenxin.Lib.House.Entity.House_KeyReceiptionInfo dbModel = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetModel(model.ReceiptionId);

            if (dbModel!=null)
            {
                dbModel.GetKeyDay = model.GetKeyDay;
                dbModel.KeyCount = model.KeyCount;
                dbModel.ReceiptionCode = model.ReceiptionCode;
                dbModel.UpdateTime = DateTime.Now;
            }
            Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.Update(dbModel);
            return retExecResult(Constants.ExecResult.Succ, "更新成功", "");
        }
        catch (Exception ex)
        {
            return retExecResult(Constants.ExecResult.Error, "意外错误：" + ex.Message, "");
        }
    }
    //返回值説明     ：void
    //功能詳細       ：删除
    //作成者         ：chen.yugong 
    //作成日         ：2010-03-01
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string delKeyReceiption(HttpContext context)
    {
        try
        {
            //转换成实体
            string modelid = context.Request["modelid"];
            if (modelid == null)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "标识丢失，请联系管理员！");
            Chenxin.Lib.House.Entity.House_KeyReceiptionInfo model = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetModel(new Guid(modelid));
            if (model == null)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "该条钥匙使用信息不存在！");
            Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.Delete(model.ReceiptionId);

            Chenxin.Lib.House.Entity.House_BaseInfo house_BaseInfo = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(model.HouseId);
            house_BaseInfo.IsHavekey = false;
            Chenxin.Lib.House.DAL.House_BaseInfo.Update(house_BaseInfo);
            //清除缓存
            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, model.HouseId);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            cs.Delete(strCachKey);
            
            return string.Format("{{success:'1',msg:'{0}',data:''}}", "删除成功！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }

    }
    //返回值説明     ：void
    //功能詳細       ：删除
    //作成者         ：chen.yugong 
    //作成日         ：2010-03-01
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string delKeyUseInfo(HttpContext context)
    {
        try
        {
            //转换成实体
            string modelid = context.Request["modelid"];
            if (modelid == null)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "标识丢失，请联系管理员！");
            Chenxin.Lib.House.Entity.House_KeyUsedInfo model = Chenxin.Lib.House.DAL.House_KeyUsedInfo.GetModel(new Guid(modelid));
            if (model == null)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "该条钥匙使用信息不存在！");
            Chenxin.Lib.House.DAL.House_KeyUsedInfo.Delete(model.KeyId);

            return string.Format("{{success:'1',msg:'{0}',data:''}}", "删除成功！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }

    }
    //*******************************************
    //返回值説明     ：响应字符串
    //功能詳細       ：权限检查
    //作成者         ：chenyg
    //作成日         ：2010-05-19
    //修改者         ：
    //修改日         ：
    //*******************************************
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        if (context.Request["op"] != null)
        {
            string op = context.Request["op"].ToLower();
            //如果是钥匙添加和钥匙使用添加
            if (op.Equals("checkpermit") && ("add".Equals(context.Request["code"]) || "addkeyuse".Equals(context.Request["code"]) || "edit".Equals(context.Request["code"]) || "editkeyuse".Equals(context.Request["code"])))
            {

                if ("add".Equals(context.Request["code"]))
                {
                    string keyid = context.Request["keyid"];
                    Chenxin.Lib.House.Entity.House_BaseInfo model = null;
                    
                    if ("add".Equals(context.Request["code"]))
                    {
                        try
                        {
                            model = (Chenxin.Lib.House.Entity.House_BaseInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_BaseInfo));
                        }
                        catch (Exception e)
                        {
                            strMsg = "{success:0,msg:'" + e.Message + "',data:''}";
                            return false;
                        }
                    }

                    //所有权限
                    if (CurrentUserInfo.ContainsPermit(Constants.Permit_KeyAdd_All))
                    {
                        strMsg = "{success:1,msg:'',data:{permit:true}}";
                        return true;
                    }
                    //城市级权限
                    else if (CurrentUserInfo.ContainsPermit(Constants.Permit_KeyAdd_City))
                    {
                        if (CurrentUserInfo.CityId.Equals(model.CityId))
                        {
                            strMsg = "{success:1,msg:'',data:{permit:true}}";
                            return true;
                        }
                        else
                        {
                            strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                            return false;
                        }
                    }
                    else
                    {
                        if (CurrentUserInfo.CompanyId.Equals(model.CompanyId))
                        {
                            strMsg = "{success:1,msg:'',data:{permit:true}}";
                            return true;
                        }
                        else
                        {
                            strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                            return false;
                        }
                    }
                }
                else
                {
                    Chenxin.Lib.House.Entity.House_KeyReceiptionInfo model = null;
                    
                    //传递参数用
                    System.Collections.Hashtable per = new System.Collections.Hashtable();
                    System.Collections.Hashtable confine = new System.Collections.Hashtable();
                    string currentId = string.Empty;

                    //修改钥匙
                    if ("edit".Equals(context.Request["code"]))
                    {
                        currentId = context.Request["currentId"];
                        model = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetModel(new Guid(currentId));
                        if (model == null)
                        {
                            strMsg = "{success:0,msg:'钥匙信息获取失败！',data:''}";
                            return false;
                        }
                        //加如权限项
                        per.Add("ALL", Constants.Permit_KeyEdit_All);
                        per.Add("CITY", Constants.Permit_KeyEdit_City);
                        per.Add("COMPANY", Constants.Permit_KeyEdit_Company);
                        per.Add("DEPART", Constants.Permit_KeyEdit_Department);
                        //加入范围
                        confine.Add("CityId", model.CityId);
                        confine.Add("CompanyId", model.CompanyId);
                        confine.Add("OperatorId", model.AddPersonId);
                        //检查权限
                        return CheckPermint(per, confine, checkDepartPermit(model.DepartId, context.Request["code"]), out strMsg);
                    }
                    //使用钥匙
                    if ("addkeyuse".Equals(context.Request["code"]))
                    {
                        currentId = context.Request["keyid"];
                        model = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetModel(new Guid(currentId));
                        if (model == null)
                        {
                            strMsg = "{success:0,msg:'钥匙信息获取失败！',data:''}";
                            return false;
                        }
                        //加如权限项
                        per.Add("ALL", Constants.Permit_KeyUse_All);
                        per.Add("CITY", Constants.Permit_KeyUse_City);
                        per.Add("COMPANY", Constants.Permit_KeyUse_Company);
                        per.Add("DEPART", Constants.Permit_KeyUse_Department);
                        //加入范围
                        confine.Add("CityId", model.CityId);
                        confine.Add("CompanyId", model.CompanyId);
                        confine.Add("OperatorId", model.AddPersonId);
                        //检查权限
                        return CheckPermint(per, confine, checkDepartPermit(model.DepartId, context.Request["code"]), out strMsg);
                    }
                    //使用编辑钥匙
                    if ("editkeyuse".Equals(context.Request["code"]))
                    {
                        currentId = context.Request["currentId"];
                        Chenxin.Lib.House.Entity.House_KeyUsedInfo modeluse = null;
                        modeluse = Chenxin.Lib.House.DAL.House_KeyUsedInfo.GetModel(new Guid(currentId));
                        if (modeluse == null)
                        {
                            strMsg = "{success:0,msg:'钥匙使用信息获取失败！',data:''}";
                            return false;
                        }
                        model = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetModel(modeluse.KeyReceiptionId);
                        if (modeluse == null)
                        {
                            strMsg = "{success:0,msg:'钥匙信息获取失败！',data:''}";
                            return false;
                        }
                        //加如权限项
                        per.Add("ALL", Constants.Permit_KeyEditUse_All);
                        per.Add("CITY", Constants.Permit_KeyEditUse_City);
                        per.Add("COMPANY", Constants.Permit_KeyEditUse_Company);
                        per.Add("DEPART", Constants.Permit_KeyEditUse_Department);
                        //加入范围
                        confine.Add("CityId", model.CityId);
                        confine.Add("CompanyId", model.CompanyId);
                        confine.Add("OperatorId", model.AddPersonId);
                        //检查权限
                        return CheckPermint(per, confine, checkDepartPermit(model.DepartId, context.Request["code"]), out strMsg);
                    }
                }
            }
        }
        strMsg = "{success:1,msg:'',data:{permit:true}}";
        return true;
    }

    public bool checkDepartPermit(Guid departId, string op)
    {
        //检查有无权限
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendFormat(" (Departid = '{0}' AND  Userid= '{1}') ", departId, CurrentUserInfo.UserId);
        System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation> list = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetListArray(sb.ToString());
   
        if (list!=null && list.Count > 0)
        {
            Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation hrp = list[0];
            //修改钥匙
            if ("edit".Equals(op))
            {
                return hrp.EditKey;
            }
            //使用钥匙
            if ("addkeyuse".Equals(op))
            {
                return hrp.UseKey;
            }
            //使用编辑钥匙
            if ("editkeyuse".Equals(op))
            {
                return hrp.EditKeyUsing;
            }
        }
        return false;
    }

}